package com.winkyle.woodenfish.presenter;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.winkyle.woodenfish.mvpview.BaseMvpView;
import com.winkyle.woodenfish.rx.HttpSubscriber;
import com.winkyle.woodenfish.util.RetrofitUtil;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * @author winkyle
 * @date 2018/06/13
 * @description p层（页面接口层）所有Presenter的基类，并不强制实现这些方法，有需要在重写
 */
public class BaseMvpPresenter<V extends BaseMvpView> {
    /**
     * V层view
     */
    private V mView;
    /**
     * @description Presenter被创建后调用
     * @param savedState 被意外销毁后重建后的Bundle
     * @return
     */
    public void onCreatePersenter(@Nullable Bundle savedState) {
        Log.e("perfect-mvp","P onCreatePersenter = ");
    }
    /**
     * @description 绑定View
     * @return
     */
    public void onAttachMvpView(V mvpView) {
        mView = mvpView;
        Log.e("perfect-mvp","P onResume");
    }
    /**
     * @description 解除绑定View
     * @return
     */
    public void onDetachMvpView() {
        mView = null;
        Log.e("perfect-mvp","P onDetachMvpView = ");
    }
    /**
     * @description Presenter被销毁时调用
     * @return
     */
    public void onDestroyPersenter() {
        Log.e("perfect-mvp","P onDestroy = ");
    }
    /**
     * @description 在Presenter意外销毁的时候被调用，它的调用时机和Activity、Fragment、View中的onSaveInstanceState
     * 时机相同
     * @param outState
     * @return
     */
    public void onSaveInstanceState(Bundle outState) {
        Log.e("perfect-mvp","P onSaveInstanceState = ");
    }
    /**
     * @description 获取V层接口View
     * @return 返回当前MvpView
     */
    public V getMvpView() {
        return mView;
    }

    /**
     * @description 获取设备号
     * @return
     */
    public String getDeviceNumber(){
        TelephonyManager tm = (TelephonyManager)mView.getContext().getSystemService(Context.TELEPHONY_SERVICE);
        String deviceId = tm.getDeviceId();
        return deviceId;
    }

    /**
     * @description 创建一个RetrofitApi并返回，用于调用该RetrofitApi的访问数据的方法
     * @return
     */
    public <T> T createRetrofitApi(Class<T> clazz) {
        return RetrofitUtil.getInstance(mView.getContext()).getRetrofit().create(clazz);
    }

    /**
     * @description 观察者订阅网络请求
     * @param observable 主题
     * @param httpSubscriber 观察者
     * @return
     */
    public void subscribeToRequest(Observable observable, HttpSubscriber httpSubscriber) {
        observable
                .subscribeOn(Schedulers.io())  // 网络请求切换在io线程中调用
                .unsubscribeOn(Schedulers.io())// 取消网络请求放在io线程
                .observeOn(AndroidSchedulers.mainThread())// 观察后放在主线程调用
                .subscribe(httpSubscriber);
    }
}